package com.by.yz.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.Register.DoctorREST;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.custom.CircleNetworkImageView;
import com.by.yz.custom.TechnologyTeamDividerItemDecoration;
import com.by.yz.entity.Doctorbean;
import com.by.yz.entity.TechnologyTeam1;
import com.by.yz.loginUtil.FindDoctorRESTFul;
import com.by.yz.util.ToJSonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by John on 2016/10/13.
 */
public class FindDoctorResultActivity extends BaseActivity implements View.OnClickListener{

    private EditText look_auto;
    private TextView search;  //查找
    private String text;
    private RecyclerView resultListview;
    String seriesName;
    List<Doctorbean> datas=new ArrayList<Doctorbean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_doctor_result);
        setToolbarTitle("搜索结果");
        initDatas();
        initView();

    }

    private void initDatas(){
        seriesName = getIntent().getStringExtra("searchString");
        Log.e("searchString",seriesName);
        if(isNetworkAvailable(FindDoctorResultActivity.this)){
            DoctorREST doctorREST=new DoctorREST();
            doctorREST.getDoctorRESTo(new DoctorREST.MyGetCallBack() {
                @Override
                public void ok(JSONArray response) throws JSONException {
                    for (int i = 0; i < response.length(); i++) {
                        Doctorbean doctorbean;
                        JSONObject jsonObject = response.getJSONObject(i);
                        doctorbean = ToJSonObject.jsonToBean(jsonObject.toString(),Doctorbean.class);
                        if(doctorbean.getDoctorname().indexOf(seriesName)!=-1 || doctorbean.getTextHospital().getHospital().indexOf(seriesName)!=-1 || doctorbean.getDepartment().getDepartment().indexOf(seriesName)!=-1) {
                            datas.add(doctorbean);
                            resultListview.setVisibility(View.VISIBLE);
                        }
                    }
                }
                @Override
                public void error(String error) {
                Log.e("qwq","error2");
            }
         });
        }else{
            //无网络连接情况
            new AlertDialog.Builder(FindDoctorResultActivity.this)
                    .setTitle("提示!")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("检测到您还没开启网络，请开启")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    startActivity(new Intent(
                                            Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                }
                            }).show();
        }

    }

    private void initView() {
        look_auto = (EditText) findViewById(R.id.look_auto);
        search = (TextView) findViewById(R.id.lv_look);
        search.setOnClickListener(this);
        //搜索结果展示
        resultListview=(RecyclerView) findViewById(R.id.result_listview);
        resultListview.setLayoutManager(new LinearLayoutManager(resultListview.getContext()));
        resultListview.setAdapter(new SimpleStringRecyclerViewAdapter(FindDoctorResultActivity.this,
                datas) );
        resultListview.addItemDecoration(new TechnologyTeamDividerItemDecoration(this,TechnologyTeamDividerItemDecoration.VERTICAL_LIST));

        setToolbarTitle("搜索结果");

    }

    public static class SimpleStringRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {

        private final TypedValue mTypedValue = new TypedValue();
        private int mBackground;
        private List<Doctorbean> mValues;

        public static class ViewHolder extends RecyclerView.ViewHolder {
            public Doctorbean tt = new Doctorbean();

            public final View mView;
            public final CircleNetworkImageView mImageView;
            public final TextView doctorName;
            public final TextView textHospital;
            public final TextView department;
            public final TextView instruc;
            public final TextView doctorPosition;

            public ViewHolder(View view) {
                super(view);
                mView = view;
                mImageView = (CircleNetworkImageView) view.findViewById(R.id.avatar);
                doctorName = (TextView) view.findViewById(R.id.doctorName);
                textHospital = (TextView) view.findViewById(R.id.textHospital);
                department = (TextView) view.findViewById(R.id.department);//隶属科室
                instruc =(TextView) view.findViewById(R.id.textSubDescripting);
                doctorPosition=(TextView)view.findViewById(R.id.doctorPosition);
            }
        }

        public Doctorbean getValueAt(int position) {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List<Doctorbean> items) {
            context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
            mBackground = mTypedValue.resourceId;
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.find_doctor_result_item, parent, false);
            // view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.tt = mValues.get(position);
            holder.doctorName.setText(mValues.get(position).getDoctorname());
            holder.textHospital.setText(mValues.get(position).getTextHospital().getHospital());
            holder.department.setText(mValues.get(position).getDepartment().getDepartment());
            holder.instruc.setText(mValues.get(position).getResume());
            holder.doctorPosition.setText(mValues.get(position).getPosition());
            holder.mImageView.setDefaultImageResId(R.mipmap.login_logo1);
            holder.mImageView.setErrorImageResId(R.mipmap.login_error);
            holder.mImageView.setImageUrl(mValues.get(position).getmImageView(), App.imageLoader);
//            Glide.with(holder.mImageView.getContext())
//                    .load(mValues.get(position).getmImageView())
//                    .fitCenter()
//                    .into(holder.mImageView);
            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, Famous_doctor_detail.class);
                    intent.putExtra("Doctor",holder.tt);
                    context.startActivity(intent);
                }
            });

        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }
    }

    private void openSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(look_auto,InputMethodManager.SHOW_FORCED);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lv_look:
                text = look_auto.getText().toString().trim();
                if (!text.equals("")) {
                    DoctorREST doctorREST=new DoctorREST();
                    doctorREST.getDoctorRESTo(new DoctorREST.MyGetCallBack() {
                        @Override
                        public void ok(JSONArray response) throws JSONException {
                            datas.clear();
                            boolean flag = true;
                            for (int i = 0; i < response.length(); i++) {
                                Doctorbean doctorbean;
                                JSONObject jsonObject = response.getJSONObject(i);
                                doctorbean = ToJSonObject.jsonToBean(jsonObject.toString(),Doctorbean.class);
                                if(doctorbean.getDoctorname().indexOf(text)!=-1||doctorbean.getDepartment().getDepartment().indexOf(text)!=-1||doctorbean.getTextHospital().getHospital().indexOf(text)!=-1) {
                                    flag = false;
                                    datas.add(doctorbean);
                                    resultListview.setVisibility(View.VISIBLE);
                                    openSoftInput();
                                    initView();
                                }
                            }
                            if(flag){
                                Log.e("--none--","没有搜索到对应信息");
                                resultListview.setVisibility(View.GONE);
                            }
                        }
                        @Override
                        public void error(String error) {
                            Log.e("qwq","error2");
                        }
                    });
                } else {
                    Toast.makeText(FindDoctorResultActivity.this, "请输入查找内容", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    /*
* 判断是否有网络
*/
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        } else {
            // 如果仅仅是用来判断网络连接　　　　　　
            // 则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null) {
                Log.e("hj","isNetworkAvailable - 是否有网络： "+ networkInfo.isAvailable());
                return true;
            } else {
                Log.e("hj", "isNetworkAvailable - 完全没有网络！");
                return false;
            }
        }
    }
}
